package cn.tedu.springbootdemo.controller;

import cn.tedu.springbootdemo.bean.Post;
import cn.tedu.springbootdemo.service.PostService;
import com.alibaba.excel.EasyExcel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;

@RequestMapping("/export")
@RestController
public class ExportController {

    @Autowired
    PostService postService;

    @GetMapping("/posts")
    public void exportPosts(HttpServletResponse response) throws Exception {
        List<Post> posts= postService.findAllPosts();
        // Excel 文件的ContentType application/vnd.ms-excel
        response.setContentType("application/vnd.ms-excel");
        //设置下载保存时候的文件名
        String filename="帖子列表.xlsx";
        filename = URLEncoder.encode(filename, "UTF-8");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename+"\"");
        OutputStream out = response.getOutputStream();
        //发送文件内容
        EasyExcel.write(out, Post.class).sheet("发贴内容").doWrite(posts);

    }

}
